package cn.com.nes.common.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class HttpUtils {

    /**
     * GET方式调接口,带header
     * @param url		请求路径
     * @param header	头信息
     * @param params	JSON格式参数
     * @return
     */
    public static JSONObject get(String url, Map<String,String> header, JSONObject params) {
        return JSON.parseObject(sendGet(url, params.toJSONString(), header));
    }

    /**
     * GET方式调接口,带header
     * @param url		请求路径
     * @param header	头信息
     * @param params	JSON格式参数
     * @return
     */
    public static JSONObject get(String url, Map<String,String> header, String params) {
        return JSON.parseObject(sendGet(url, params, header));
    }

    /**
     * POST方式调接口,带header
     * @param url		请求路径
     * @param header	头信息
     * @param params	JSON格式字符串
     * @return
     */
    public static JSONObject post(String url, Map<String,String> header, String params) {
        return JSON.parseObject(sendPost(url, params, header));
    }

    /**
     * POST方式调接口,带header
     * @param url		请求路径
     * @param header	头信息
     * @param params	JSON格式参数
     * @return
     */
    public static JSONObject post(String url, Map<String,String> header, JSONObject params) {
        return JSON.parseObject(sendPost(url, params.toJSONString(), header));
    }

    /**
     * 发送get请求
     * 参数设置：？param=val¶m2=val2
     *
     * @author TF
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            //创建URL对象、
            URL urlGet = new URL(url + "?" + param);
            System.out.println(urlGet);
            //打开URL连接
            URLConnection connection = urlGet.openConnection();
            //设置请求头信息
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
            connection.setRequestProperty("contentType", "UTF-8");
            //建立连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    
    public static String sendGet(String url, String param, Map<String,String> header) {
        String result = "";
        BufferedReader in = null;
        try {
            //创建URL对象、
            URL urlGet = new URL(url + "?" + param);
            System.out.println(urlGet);
            //打开URL连接
            URLConnection connection = urlGet.openConnection();
            //设置请求头信息
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
            connection.setRequestProperty("contentType", "UTF-8");

            Set<Entry<String, String>> entrySet = header.entrySet();
            Iterator<Entry<String, String>> iterator = entrySet.iterator();
            while(iterator.hasNext()){
            	Entry<String, String> next = iterator.next();
            	connection.setRequestProperty(next.getKey(), next.getValue());
            }
            //建立连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 发送post请求
     * 参数设置param1=val1&m2=val2
     */
    public static String sendPost(String url, String param) {
        String result = "";
        BufferedReader in = null;
        OutputStreamWriter out = null;
        try {
            //创建URL对象、
            URL urlPost = new URL(url);
            //打开URL连接
            URLConnection connection = urlPost.openConnection();
            HttpURLConnection conn = (HttpURLConnection) connection;
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            System.out.println("error");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 发送post请求
     * 参数设置param1=val1&m2=val2
     *
     * */
    public static String sendPost(String url, byte[] param, Map<String,String> header){
        String result = "";
        BufferedReader in = null;
        OutputStream out = null;
        try {
            //创建URL对象、
            URL urlPost = new URL(url);
            //打开URL连接
            URLConnection connection = urlPost.openConnection();
            HttpURLConnection conn = (HttpURLConnection) connection;
            conn.setRequestMethod("POST");
         // 设置连接主机服务器超时时间：15000毫秒
            conn.setConnectTimeout(30000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            conn.setReadTimeout(30000);
         // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
         // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            conn.setRequestProperty("Content-Type", "application/json");
            Set<Entry<String, String>> entrySet = header.entrySet();
            Iterator<Entry<String, String>> iterator = entrySet.iterator();
            while(iterator.hasNext()){
            	Entry<String, String> next = iterator.next();
            	conn.setRequestProperty(next.getKey(), next.getValue());
            }


            // 获取URLConnection对象对应的输出流
            out = conn.getOutputStream();
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            System.out.println("error");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String sendPost(String url, String param, Map<String,String> header) {
        return sendPost(url, param.getBytes(), header);
    }

    public static String submitDataByDoPostForJson( String path,byte[] jsondata,Map<String,String> header) {
		HttpURLConnection urlConn = null;
		try {
			URL Url = new URL(path);
			urlConn = (HttpURLConnection) Url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setConnectTimeout(30000);// 设置连接主机超时（单位：毫秒）
			urlConn.setReadTimeout(30000);
			urlConn.setDoOutput(true);
			urlConn.setUseCaches(false);
			urlConn.setRequestProperty("Connection", "Keep-Alive");
			urlConn.setRequestProperty("Content-Type",
					"application/json");
			urlConn.setRequestProperty("Content-Length",
					String.valueOf(jsondata.length));
			urlConn.setRequestProperty("Accept", "application/json; charset=utf-8");
			Set<Entry<String, String>> entrySet = header.entrySet();
            Iterator<Entry<String, String>> iterator = entrySet.iterator();
            while(iterator.hasNext()){
            	Entry<String, String> next = iterator.next();
            	urlConn.setRequestProperty(next.getKey(), next.getValue());
            }
			OutputStream os = urlConn.getOutputStream();
			os.write(jsondata,0,jsondata.length);
			os.flush();
			os.close();
			int i = urlConn.getResponseCode();
			System.out.println(i);
			if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = urlConn.getInputStream();
				return changeStreamToString(is);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
			}
		}
		return null;
	}

    private static String changeStreamToString(InputStream in) {
		StringBuffer sb = new StringBuffer();
		String readIn = null;
		try {
			BufferedReader re = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			while ((readIn = re.readLine()) != null) {
				sb.append(readIn);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

    public static String sendJSONPost(String url, String json) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        OutputStreamWriter out = null;
        try {
            //创建URL对象、
            URL urlPost = new URL(url);
            //打开URL连接
            URLConnection connection = urlPost.openConnection();
            HttpURLConnection conn = (HttpURLConnection) connection;
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            // 发送请求参数
            byte[] input = json.getBytes(StandardCharsets.UTF_8);
            conn.getOutputStream().write(input);
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("API 调用失败：{}", e.getMessage());
        }

        return result.toString();
    }
    
    public static Map<String,String>  getPhoneAddress(String phone) {
    	String s = HttpUtils.sendGet("https://cx.shouji.360.cn/phonearea.php","number="+phone);
    	return unicodeToString(s) ;
    }
    
	public static Map<String,String> unicodeToString(String str) {
		Map<String,String> map = new HashMap<String, String>();
		try {
			Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
			Matcher matcher = pattern.matcher(str);
			char ch;
			while (matcher.find()) {
				// group 6728
				String group = matcher.group(2);
				// ch:'木' 26408
				ch = (char) Integer.parseInt(group, 16);
				// group1 \u6728
				String group1 = matcher.group(1);
				str = str.replace(group1, ch + "");
			}
			JSONObject e = JSONObject.parseObject(str);
			String province = (String) e.getJSONObject("data").get("province") ;
			String city = (String) e.getJSONObject("data").get("city") ;		
			map.put("province", province);
			map.put("city", city);
		}catch (Exception e) {
			log.error("手机号归属地结果转换失败！原因：{}", e.getMessage());
		}

		return map;
	}
	
	public static String submitDataByDoPostJson(String jsondata, String path) {
		HttpURLConnection urlConn = null;
		try {
            log.debug(path);
            URL Url = new URL(path);
			urlConn = (HttpURLConnection) Url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setConnectTimeout(30000);// 设置连接主机超时（单位：毫秒）
			urlConn.setReadTimeout(30000);
			urlConn.setDoOutput(true);
			urlConn.setUseCaches(false);
			urlConn.setRequestProperty("Connection", "Keep-Alive");
			urlConn.setRequestProperty("Charset", "UTF-8");
			urlConn.setRequestProperty("Content-Type",
					"application/json");
			urlConn.setRequestProperty("Content-Length",
					String.valueOf(jsondata.getBytes().length));
			OutputStream os = urlConn.getOutputStream();
			os.write(jsondata.getBytes("UTF-8"));
			os.flush();
			os.close();
			if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = urlConn.getInputStream();
				String str = changeStreamToString(is) ;
				if(str!=null){
					str = str.replaceAll(" ", "") ;
					str = str.replaceAll("	", "") ;
				}

				return str;
			}else{
				return "{'code':9,'msg':'服务器返回异常，请重试！'}";
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
			}
		}
		return "{'code':9,'msg':'发送命令失败，请重试！'}";
	}
    public static String sendCommand(String dtuId, String protocolId,long dtuTypeId,int IsQueryCommand,String commandId,String token,String url) {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("dtuId",dtuId);
        jsonObject.put("deviceProtocolId",protocolId);
        jsonObject.put("dtuTypeId",dtuTypeId);
        jsonObject.put("nodeid","");
        jsonObject.put("isQueryCommand",IsQueryCommand);
        jsonObject.put("commandId",commandId);
        Map<String,String> header=new HashMap<>();
        header.put("key",token);
        String result=HttpUtils.sendPost(url,jsonObject.toString().getBytes(StandardCharsets.UTF_8),header);
        return result;
    }
    public static void main(String[] args) {
    	String url = "https://restapi.amap.com/v5/place/around?key=4a426fb6dd527fccb997391577d88e48&keywords=热泵&location=116.473168,39.993015&offset=25&page=10" ;
    	String res = HttpUtils.submitDataByDoPostJson("", url);
        System.out.println(res);
    }
}
